import { getKeyRouter, getLoadMapList, getTenantID } from '@/utils';
import { Button, Descriptions, Drawer, Form, Space, Table, Select } from 'antd';
import type { SelectProps } from 'antd';
import React, { useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { PlusCircleOutlined, MinusCircleOutlined, ClearOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import '../common/styles.less';
import { ILoadMapTypeAll } from '@/common';
import { getExtractTableConfig } from '../mconfig';
import _ from 'lodash';

export const ExtractListDrawer = React.forwardRef<Record<string, any>>(({ visible, onClose, expertDataSource }: Record<string, any>, ref) => {
  const prefixCls = 'source-drawer-';

  /** 单位列表-屏蔽单位使用 */
  const [unitList, setUnitList] = useState<any[]>([]); // 单位列表
  useEffect(() => {
    if (expertDataSource?.length > 0) {
      const mapData = expertDataSource.map((item) => {
        return {
          label: item?.companyName,
          value: item?.companyName,
        };
      });
      setUnitList(_.uniqWith(mapData, _.isEqual));
    }
  }, [expertDataSource]);

  /**extract表单的ref*/
  const [extractForm] = Form.useForm();

  useImperativeHandle(
    ref,
    () =>
      ({
        firstForm: extractForm,
      } as any),
  );

  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.EXPERTS_TYPE}`];
  const { loadMapInfo: loadMapInfoList, mapLoading } = getLoadMapList(loadMdicIds);

  /** 保存抽选数据 */
  const [extractDataSource, setExtractDataSource] = useState<Record<string, any>[]>(extractForm?.getFieldValue('extractTable'));

  /** 默认进来有一个抽选数据 */
  // useEffect(() => {
  //   if (loadMapInfoList?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_TYPE}`]?.length > 0) {
  //     let newData = [
  //       {
  //         key: `extractTable-${getKeyRouter()}${getKeyRouter()}`,
  //         expertType: loadMapInfoList?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_TYPE}`][0].id,
  //         count: 1,
  //       },
  //     ];
  //     setMaterialDataSource(newData);
  //   }
  // }, [loadMapInfoList]);

  useEffect(() => {
    extractForm?.setFieldsValue({
      extractTable: extractDataSource,
    });
  }, [extractDataSource]);

  /** 添加抽选 */
  const addMaterialCallback = () => {
    const addItemObj: Record<string, any> = {
      key: `extractTable-${getKeyRouter()}${getKeyRouter()}`,
      count: null,
      expertType: null,
    };

    setExtractDataSource((_prevState: Record<string, any>[]) => {
      const materFormValue: Record<string, any>[] = extractForm?.getFieldValue('extractTable')?.length > 0 ? extractForm?.getFieldValue('extractTable') : [];
      let newMaterial: Record<string, any>[] = [...materFormValue];
      newMaterial?.push(addItemObj);
      return newMaterial;
    });
  };

  /** 删除抽选 */
  const delMaterialCallback = (resObj: Record<string, any>) => {
    setExtractDataSource((_prevState: Record<string, any>[]) => {
      const newDetailList: Record<string, any>[] = extractForm?.getFieldValue('extractTable')?.length > 0 ? extractForm?.getFieldValue('extractTable') : [];
      const newMaterial: Record<string, any>[] = newDetailList?.filter((item: any) => {
        if (item?.id) {
          return item?.id != resObj?.id;
        } else {
          return item?.key != resObj?.key;
        }
      });
      return newMaterial;
    });
  };

  /** 表格行配置 */
  const columnsMemo = useMemo(() => {
    return getExtractTableConfig(addMaterialCallback, delMaterialCallback, extractForm, loadMapInfoList, mapLoading, unitList);
  }, [loadMapInfoList, mapLoading, unitList]);

  /** 清空 */
  const onFilter = () => {
    extractForm.resetFields();
    setExtractDataSource([]);
  };

  const footer = (
    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
      <Space>
        <Button
          onClick={onClose}
          // icon={<MinusCircleOutlined />}
        >
          关闭
        </Button>
        <Button
          type="primary"
          // icon={<ClearOutlined />}
          onClick={onFilter}
        >
          清除
        </Button>
      </Space>
    </div>
  );

  return (
    <Drawer
      open={visible}
      closable={false}
      title={<span>抽选专家</span>}
      style={{ position: 'absolute', height: '100%', overflow: 'hidden' }}
      width={document.body.clientWidth * 0.4}
      headerStyle={{
        padding: '.5rem',
      }}
      bodyStyle={{
        padding: 0,
        overflowX: 'hidden',
        overflowY: 'auto',
      }}
      placement="right"
      getContainer={document.querySelector('.ant-modal-body') as any}
      // getContainer={false}
      mask={false}
      // className={prefixCls + 'detailHandleCheck'}
      onClose={onClose}
      extra={
        <Space>
          <Button
            type={'link'}
            size={'small'}
            icon={<PlusCircleOutlined />}
            className="manageBtntTxtStyle"
            onClick={() => {
              addMaterialCallback();
            }}
          >
            添加
          </Button>
        </Space>
      }
      footer={footer}
    >
      <ScrollBarLayout
        style={{
          padding: '1rem',
        }}
      >
        <div className={pageStyles['fromView-styles']} style={{ padding: '5px 0' }}>
          {/* <Descriptions bordered size="small">
              <Descriptions.Item label="屏蔽单位" labelStyle={{ whiteSpace: 'nowrap', width: '100px' }}>
                <Select mode="multiple" allowClear style={{ width: '100%' }} placeholder="选择屏蔽单位" onChange={onFilterUnit} options={unitList} />
              </Descriptions.Item>
            </Descriptions> */}
          <Form form={extractForm} style={{ marginTop: 20 }}>
            <div className={'list-table-extract-drawer'}>
              <Form.Item name="extractTable" valuePropName="dataSource">
                <Table columns={columnsMemo} bordered size="small" dataSource={extractDataSource} rowKey={'key'} pagination={false} />
              </Form.Item>
            </div>
          </Form>
        </div>
      </ScrollBarLayout>
    </Drawer>
  );
});
